﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using DTO;

namespace DA
{
    public class QC_BangDA:DBConnection
    {
        // hàm tạo
        public QC_BangDA()
        {
            sqlCommand.Connection = sqlConnection;
        }
        // lấy tất cả
        public DataSet GetAll()
        {
            var ds = new DataSet();
            const string query = "select * from QC_BANG";
            if (open())
            {
                sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
                sqlDataAdapter.Fill(ds);
            }
            close();
            return ds;
        }
        // thêm 
        public int Add(QC_BangDTO item)
        {
            var query = String.Format("insert into QC_BANG values('{0}','{1}'); select SCOPE_IDENTITY();", 
                item.MaND, item.MaChiTietBang);
            sqlCommand.CommandText = query;
            try
            {
                open();
                var idRe = -1;
                sqlCommand.CommandText = query;
                var re = sqlCommand.ExecuteScalar().ToString();
                idRe = Int32.Parse(re);
                close();
                return idRe;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return -1;
            }
        }
        // sửa
        public bool Update(QC_BangDTO qcbang)
        {
            var query = String.Format("Update QC_BANG set MaND = '{0}',MaChiTietBang='{1}' where MaQCBang = '{2}'", 
                qcbang.MaND, qcbang.MaChiTietBang, qcbang.MaQCBang);
            sqlCommand.CommandText = query;

            try
            {
                open();
                sqlCommand.ExecuteNonQuery();
                sqlCommand.Parameters.Clear();
                close();
                return true;
            }
            catch (SqlException s)
            {
                Console.WriteLine(s.Message);
                return false;
            }
        }
        // xóa 
        public bool Delete(int ma_item)
        {
            var query = "Delete from QC_BANG where MaQCBang = " + ma_item;
            sqlCommand.CommandText = query;
            try
            {
                open();
                sqlCommand.ExecuteNonQuery();
                sqlCommand.Parameters.Clear();
                close();
                return true;
            }
            catch (SqlException s)
            {
                Console.WriteLine(s.Message);
                return false;
            }
        }
    }
}
